﻿namespace ConsoleApp;

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class HeartbeatServer
{
    private List<TcpClient> connectedClients = new List<TcpClient>();
    private const int HeartbeatInterval = 5000; // 5 seconds

    public void StartListening()
    {
        var listener = new TcpListener(IPAddress.Any, 12345); // Replace with your server port
        listener.Start();

        while (true)
        {
            var client = listener.AcceptTcpClient();
            connectedClients.Add(client);

            // Start a thread to handle the client communication
            Task.Run(() => HandleClient(client));
        }
    }

    private void HandleClient(TcpClient client)
    {
        try
        {
            var stream = client.GetStream();

            // Wait for the heartbeat message from the client
            var buffer = new byte[1024];

            while (stream.Read(buffer, 0, buffer.Length) != 0)
            {
                // Process the message from the client (e.g., heartbeat)
                Console.WriteLine("Received heartbeat from client.");

                // Send a response to the client (optional)
                var response = System.Text.Encoding.ASCII.GetBytes("Heartbeat received.");
                stream.Write(response, 0, response.Length);

                // Update the last heartbeat time for the client
                UpdateLastHeartbeat(client);
            }
        }
        catch (Exception ex)
        {
            // Client disconnected or an error occurred
            Console.WriteLine("Client disconnected: " + ex.Message);
            connectedClients.Remove(client);
            client.Close();
        }
    }

    private void UpdateLastHeartbeat(TcpClient client)
    {
        // Update the last heartbeat time for the client in your data structure
        // (e.g., using a dictionary with client as key and last heartbeat time as value)
    }

    public List<TcpClient> GetOnlineClients()
    {
        // Check the last heartbeat time for each client and return the list of online clients
        return connectedClients.Where(client => client.Connected).ToList();
    }
}